package com.hhf.feiojcodesandbox.utils;

import cn.hutool.dfa.WordTree;
import com.hhf.feiojcodesandbox.model.ExecuteCodeResponse;
import com.hhf.feiojcodesandbox.model.ExecuteMessage;
import com.hhf.feiojcodesandbox.model.JudgeInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StopWatch;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @Author hhf
 * @Date 2024/10/29
 * @Description
 */
@Slf4j
public class ProcessUtils {

    private static final long TIME_EXCEED_LIMIT = 1000 * 5L;


    public static ExecuteMessage runProcessAndGetMessage(Process runProcess, String optionName) {
        ExecuteMessage executeMessage = new ExecuteMessage();
        StopWatch stopWatch = new StopWatch();

        //守护线程,只允许运行规定时间 ,超出时间限制,中止代码的运行
        if ("运行".equals(optionName)){
            new Thread(() ->{
                try {
                    log.info("开启守护线程...");
                    Thread.sleep(TIME_EXCEED_LIMIT);
                    //如果还在执行,则终止
                    if (runProcess.isAlive()){
                        runProcess.destroy();
                    }
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }).start();
        }


        try {
            // 等待程序执行，获取错误码
            stopWatch.start();
            int exitValue = runProcess.waitFor();
            stopWatch.stop();
            executeMessage.setTime(stopWatch.getLastTaskTimeMillis());
            executeMessage.setExitValue(exitValue);
            // 正常退出
            if (exitValue == 0) {
                log.info("{}成功", optionName);
                // 分批获取进程的正常输出
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(runProcess.getInputStream()));
                StringBuilder compileOutputStringBuilder = new StringBuilder();
                // 逐行读取
                String line;
                while ((line = bufferedReader.readLine()) != null) {
                    compileOutputStringBuilder.append(line);
                }
                executeMessage.setMessage(compileOutputStringBuilder.toString());
            } else {
                //异常退出,记录日志
                log.warn("{}失败，错误码: {}", optionName, exitValue);
                // 分批获取进程的正常输出
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(runProcess.getInputStream()));
                StringBuilder compileOutputStringBuilder = new StringBuilder();
                // 逐行读取
                String line;
                while ((line = bufferedReader.readLine()) != null) {
                    compileOutputStringBuilder.append(line);
                }
                executeMessage.setMessage(compileOutputStringBuilder.toString());
                // 分批获取进程的错误输出
                BufferedReader errorbufferedReader = new BufferedReader(new InputStreamReader(runProcess.getErrorStream()));
                StringBuilder errorCompileOutputStringBuilder = new StringBuilder();
                // 逐行读取
                String errorLine;
                while ((errorLine = errorbufferedReader.readLine()) != null) {
                    errorCompileOutputStringBuilder.append(errorLine);
                }
                executeMessage.setErrorMessage(errorCompileOutputStringBuilder.toString());
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return executeMessage;
    }


}
